package cn.kgc.boot.tcuser.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.kgc.boot.annotation.MyDemo;
import cn.kgc.boot.tcuser.entity.TcUser;
import cn.kgc.boot.util.PoiExcelUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author XMF
 * @date 2021-06-23 10:55
 **/
@Controller
public class TestController {

    @GetMapping("test1")
    @ResponseBody
    @MyDemo(desc = "测试代码")
    public String test1(String str, String age){
        return "测试1" + str + age;
    }


    @MyDemo(desc = "测试hutool下载exl")
    @GetMapping("downExl")
    public void downExl(HttpServletResponse response){
        List<TcUser> tcUsers = new ArrayList<>();
        TcUser tcUser1 = new TcUser(1, "这是1", "111a");
        TcUser tcUser2 = new TcUser(2, "这是2", "222b");
        TcUser tcUser3 = new TcUser(3, "这是3", "333c");
        tcUsers.add(tcUser1);
        tcUsers.add(tcUser2);
        tcUsers.add(tcUser3);
        // 商品导出or模板
        List<String> headerList;
        // 使用 hutool创建exl
        ExcelWriter writer = ExcelUtil.getBigWriter();
        String[] header = {"序号", "ID", "用户名称", "密码"};
        headerList = Arrays.asList(header);
        Sheet sheet = writer.getSheet();
        writer.merge(headerList.size() - 1, "测试exl");
        writer.writeRow(headerList);
        for (int i = 0; i < headerList.size(); i++) {
            if (i == 0 || i == 1 || i == 2 || i == 3 || i == 5 || i == 6 || i == 7 || i == 8 || i == 10 || i == 11) {
                sheet.setColumnWidth(i, 10 * 256);
            } else {
                sheet.setColumnWidth(i, 20 * 256);
            }
        }
        int row = 1;
        for (TcUser tcUser : tcUsers) {
            int firstRow = row + 1;
            int lastRow = row + 1;
            int col = -1;
            PoiExcelUtil.mergeIfNeed(writer, firstRow, lastRow, ++col, col, row);
            PoiExcelUtil.mergeIfNeed(writer, firstRow, lastRow, ++col, col, tcUser.getId());
            PoiExcelUtil.mergeIfNeed(writer, firstRow, lastRow, ++col, col, tcUser.getUsername());
            PoiExcelUtil.mergeIfNeed(writer, firstRow, lastRow, ++col, col, tcUser.getPassword());
            row ++;
        }
        PoiExcelUtil.writeExcel("测试exl.xls", writer, response);
    }





}
